#include "graph_adjacency_list.h"
#include "print_graph.h"

GraphAdjList::GraphAdjList(const std::vector<std::vector<Vertex*>>& edges)
{
    // 添加所有顶点和边
    for (const std::vector<Vertex*>& edge : edges)
    {
        addVertex(edge[0]);
        addVertex(edge[1]);
        addEdge(edge[0], edge[1]);
    }
}

void GraphAdjList::remove(std::vector<Vertex*>& vec, Vertex* vet)
{
    for (int i = 0; i < vec.size(); i++)
    {
        if (vec[i] == vet)
        {
            vec.erase(vec.begin() + i);
            break;
        }
    }
}

int GraphAdjList::size()
{
    return adjList.size();
}

void GraphAdjList::addEdge(Vertex* vet1, Vertex* vet2)
{
    if (!adjList.count(vet1) || !adjList.count(vet2) || vet1 == vet2)
    {
        //throw std::invalid_argument("不存在顶点");
        //std::cerr << "不存在顶点";
    }

    // 添加边 vet1 - vet2
    adjList[vet1].push_back(vet2);
    adjList[vet2].push_back(vet1);
}

void GraphAdjList::removeEdge(Vertex* vet1, Vertex* vet2)
{
    if (!adjList.count(vet1) || !adjList.count(vet2) || vet1 == vet2)
    {
        //throw invalid_argument("不存在顶点");
    }
    // 删除边 vet1 - vet2
    remove(adjList[vet1], vet2);
    remove(adjList[vet2], vet1);
}

void GraphAdjList::addVertex(Vertex* vet)
{
    if (adjList.count(vet))
        return;
    // 在邻接表中添加一个新链表
    adjList[vet] = std::vector<Vertex*>();
}

void GraphAdjList::removeVertex(Vertex* vet)
{
    if (!adjList.count(vet))
    {
        //throw std::invalid_argument("不存在顶点");
    }
    // 在邻接表中删除顶点 vet 对应的链表
    adjList.erase(vet);
    // 遍历其他顶点的链表，删除所有包含 vet 的边
    for (auto& adj : adjList)
    {
        remove(adj.second, vet);
    }
}

void GraphAdjList::print()
{
#if 1
    std::cout << "邻接表 =" << std::endl;
    for (auto& adj : adjList)
    {
        const auto& key = adj.first;
        const auto& vec = adj.second;
        std::cout << key->val << ": ";
        //printVector(vetsToVals(vec));
    }
#endif 
}
